package dt.htwk.core;

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Arrays;
import java.util.Vector;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;

import dt.htwk.sql.DBResult;
import dt.htwk.sql.Database;
import dt.htwk.utilities.User;

public class KCLogin extends JFrame {

	private static final long serialVersionUID = 1L;
	private JPanel cards;
	private static Database iDB;
	private DBResult dbResult;
	private JComboBox cbUser;
	private User selectedUser;
	private Vector<User> user = new Vector<User>();
	private JPasswordField passwdField;
	private JPasswordField passwdField2;
	private JLabel label2;
	private JLabel title;
	private JButton btnLogin;
	private JButton btnCancel;

	

	public KCLogin(){
		super("KCLogin");
		dbResult =iDB.setConnection();
		initGUI();
		if(dbResult.getRowCount() < 1){
			setRegisterUser(true);
		}else{
			setUsers();
			setRegisterUser(false);
		}
		
	}
	
	public static void setDatabase(Database iDB) {
		KCLogin.iDB = iDB;
	}
	

	// ***************************************
	// *** EVENT HANDLER *********************
	// ***************************************
	
	protected javax.swing.event.EventListenerList listenerList =
        new javax.swing.event.EventListenerList();
	
	// This methods allows classes to register for EditorEvents
    public void addN2GLoginEventListener(KCLoginEvents listener) {
        listenerList.add(KCLoginEvents.class, listener);
    }

    // This methods allows classes to unregister for EditorEvents
    public void removeN2GLoginEventListener(KCLoginEvents listener) {
        listenerList.remove(KCLoginEvents.class, listener);
    }

    // This private class is used to fire ButtonOptions
    void fireLoginAction(ActionEvent evt) {
        Object[] listeners = listenerList.getListenerList();
        for (int i=0; i<listeners.length; i+=2) {
            if (listeners[i]==KCLoginEvents.class) {
                ((KCLoginEvents)listeners[i+1]).loginAction(evt);
            }
        }
    }

	private void initGUI(){
		
		try {
			this.setSize(400, 300);
			this.setLayout(new BorderLayout());
			this.setTitle("Note2Go Anmeldung ...");
			{
				JPanel header = new JPanel(new BorderLayout());//BorderLayout()
				header.setPreferredSize(new Dimension(400,40));
				header.setBackground(new java.awt.Color(92,108,129));
				{
					JLabel hTitle = new JLabel("  Note2Go");
					hTitle.setForeground(new java.awt.Color(230,230,230));
					hTitle.setPreferredSize(new Dimension(400,40));
					hTitle.setFont(new java.awt.Font("Verdana",1,14));
					header.add(hTitle, BorderLayout.CENTER);
				}
				
				JPanel footer = new JPanel(new BorderLayout());//BorderLayout()
				footer.setPreferredSize(new Dimension(400,40));
				footer.setBackground(new java.awt.Color(92,108,129));
				{
					JLabel fTitle = new JLabel("  Elektronische Merkzettel");
					fTitle.setForeground(new java.awt.Color(230,230,230));
					fTitle.setPreferredSize(new Dimension(300,40));
					fTitle.setFont(new java.awt.Font("Verdana",0,12));
					fTitle.setHorizontalAlignment(SwingConstants.LEFT);
					footer.add(fTitle, BorderLayout.LINE_START);
					
					JLabel fCopy = new JLabel("by D.Toepel  ");
					fCopy.setForeground(new java.awt.Color(230,230,230));
					fCopy.setPreferredSize(new Dimension(100,40));
					fCopy.setFont(new java.awt.Font("Verdana",0,12));
					fCopy.setHorizontalAlignment(SwingConstants.RIGHT);
					footer.add(fCopy, BorderLayout.LINE_END);

				}

				this.getContentPane().add(header, BorderLayout.PAGE_START);
				this.getContentPane().add(footer, BorderLayout.PAGE_END);
				this.getContentPane().add(getCards(), BorderLayout.CENTER);

			}
		} catch (Exception e) {}
	}
	
	private JPanel getCards(){//DBResult dbResult
		if(cards == null){
			cards = new JPanel(new CardLayout());
			cards.setBackground(new java.awt.Color(195,200,205));
			cards.setBorder(BorderFactory.createEmptyBorder(5,10,5,10));
			{
				JPanel content;
				content = new JPanel(new GridBagLayout());
				content.setBackground(cards.getBackground());
				{
					GridBagConstraints s = new GridBagConstraints();
					s.ipadx = 5;s.ipady = 2;
					s.weightx = 0;s.gridwidth = 1;
					s.fill = GridBagConstraints.NONE;
					s.anchor = GridBagConstraints.LINE_START;
					
					JLabel label;
					
					title = new JLabel();
					title.setForeground(new java.awt.Color(28,28,28));
					title.setFont(new java.awt.Font("Verdana",1,14));
					{
			        	s.gridx = 0;
			        	s.gridy = 0;
			        	s.gridwidth = 3;
			        	s.weightx = 1;
			        	s.weighty = 0.3;
			        	s.fill = GridBagConstraints.HORIZONTAL;
			        	content.add(title, s);
			        	s.weighty = 0;
			        	s.weightx = 0;
					}
					
					label = new JLabel("Benutzer: ");
					{
			        	s.gridx = 0;
			        	s.gridy = 1;
			        	s.gridwidth = 1;
			        	content.add(label, s);
					}
					
					cbUser = new JComboBox(user);
					cbUser.addKeyListener(getN2GKeyListener());
					cbUser.addItemListener(new ItemListener() {
						@Override
						public void itemStateChanged(ItemEvent e) {
							if(!cbUser.isEditable())
								selectedUser = (User)e.getItem();
						}
					});
					{
			        	s.gridx = 1;
			        	s.gridy = 1;
			        	content.add(cbUser, s);
					}
					
					label = new JLabel("Passwort*: ");
					{
			        	s.gridx = 0;
			        	s.gridy = 2;
			        	content.add(label, s);
					}
					
					passwdField = new JPasswordField();
					passwdField.addKeyListener(getN2GKeyListener());
					{
			        	s.gridx = 1;
			        	s.gridy = 2;
			        	content.add(passwdField, s);
					}
					
					label2 = new JLabel("Passwort**: ");
					{
			        	s.gridx = 0;
			        	s.gridy = 3;
			        	content.add(label2, s);
					}
					
					passwdField2 = new JPasswordField();
					passwdField2.addKeyListener(getN2GKeyListener());
					{
			        	s.gridx = 1;
			        	s.gridy = 3;
			        	content.add(passwdField2, s);
					}
					
					JTextArea ta = new JTextArea(
							"* Falls Sie kein Passwort benoetigen, " +
							"bitte dieses Feld leer lassen. \nBedenken Sie jedoch, " +
							"dass jeder Zugriff zu Ihren Notizen hat.\n" +
							"** Bitte Passwort zur Ueberpruefung wiederholen.");
					ta.setBorder(BorderFactory.createEmptyBorder(10,0,0,0));
					ta.setBackground(cards.getBackground());
					ta.setEditable(false);
					{
			        	s.gridx = 0;
			        	s.gridy = 4;
			        	s.weighty = 1;
			        	s.gridwidth = 3;
			        	s.fill = GridBagConstraints.BOTH;
			        	content.add(ta, s);
			        	s.fill = GridBagConstraints.NONE;
			        	s.gridwidth = 1;
			        	s.weighty = 0;
					}
					
					btnLogin = new JButton("Anmelden");
					btnLogin.setActionCommand("logged in");
					btnLogin.addKeyListener(getN2GKeyListener());
					btnLogin.setHorizontalAlignment(SwingConstants.RIGHT);
					btnLogin.addActionListener(new ActionListener() {
						@Override
						public void actionPerformed(ActionEvent evt) {
//							fireLoginAction(evt);
//							loginUser(evt);
						}
					});
					{
			        	s.gridx = 1;
			        	s.gridy = 5;
			        	s.weightx = 1;
			        	s.anchor = GridBagConstraints.LINE_END;
			        	content.add(btnLogin, s);
			        	s.weightx = 0;
					}

					btnCancel = new JButton("Abbrechen");
					btnCancel.setActionCommand("cancel");
					btnCancel.addKeyListener(getN2GKeyListener());
					btnCancel.setHorizontalAlignment(SwingConstants.RIGHT);
					btnCancel.addActionListener(new ActionListener() {
						@Override
						public void actionPerformed(ActionEvent evt) {
							fireLoginAction(evt);
						}
					});
					{
			        	s.gridx = 2;
			        	s.gridy = 5;
			        	content.add(btnCancel, s);
					}
				}
				cards.add(content, "login");
			}
		}
		
		return cards;
	}
	
	
	private void setUsers(){
		String[][] userList = dbResult.getRowContent();
		for (String[] stringUser : userList) {
			user.add(new User(stringUser[0],Integer.parseInt(stringUser[1])));
		}
		cbUser.setSelectedIndex(0);
	}
	
	private void setRegisterUser(boolean isNew){
		cbUser.setEditable(isNew);
		passwdField2.setEnabled(isNew);
		label2.setEnabled(isNew);
		if(isNew){
			cbUser.setSelectedItem(System.getProperty("user.name"));
			title.setText("Bitte registrieren Sie sich ...");
		}else{
			title.setText("Bitte melden Sie sich an ...");
		}
	}
	
//	private void loginUser(ActionEvent evt){
//		if(cbUser.isEditable()){
//			OptionsSet options = new OptionsSet(true);
//			if(Arrays.equals (passwdField.getPassword(),passwdField2.getPassword())){
//				User newUser = new User((String)cbUser.getSelectedItem(),null);
//				newUser.setPassword(passwdField.getPassword());
//				options.setLocalUser(newUser);
//				iDB.setOptions(options);
//				fireLoginAction(evt);
//			}else{
//				title.setText("Passwoerter stimmen nicht ueberein ...");
//			}
//		}else{
//			selectedUser.setPassword(passwdField.getPassword());
//			if(iDB.checkUser(selectedUser)){
//				fireLoginAction(evt);
//			}else{
//				title.setText("Anmeldung fehlgeschlagen ...");
//			}
//		}
//		
//	}
	
	private KeyListener getN2GKeyListener(){
		KeyListener key = new KeyListener() {
			
			@Override
			public void keyTyped(KeyEvent e) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void keyReleased(KeyEvent e) {
				if(e.getKeyCode() == KeyEvent.VK_ENTER){
					btnLogin.doClick();
				}else if(e.getKeyCode() == KeyEvent.VK_ESCAPE){
					btnCancel.doClick();
				}
			}
			
			@Override
			public void keyPressed(KeyEvent e) {
				// TODO Auto-generated method stub
				
			}
		};
		return key;
	}

}
